package com.maizhi.service.impl;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.maizhi.controller.menuController;
import com.maizhi.dao.BaseDaoI;
import com.maizhi.dao.UserDaoI;
import com.maizhi.httpmodel.EasyuiDataGrid;
import com.maizhi.httpmodel.EasyuiDataGridJson;
import com.maizhi.httpmodel.SessionInfo;
import com.maizhi.httpmodel.UserI;
import com.maizhi.model.Role;
import com.maizhi.model.User;
import com.maizhi.model.UID;
import com.maizhi.model.UserRole;
import com.maizhi.service.BaseServiceI;
import com.maizhi.service.UserServiceI;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.maizhi.util.Encrypt;
import com.maizhi.util.ResourceUtil;


@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserServiceI{

	BaseDaoI<User> baseDao;
	BaseDaoI<UserRole> userRoleDao;
	BaseDaoI<Role> roleDao;

	
	private Logger log = Logger.getLogger(UserServiceImpl.class);
	
	public BaseDaoI<Role> getRoleDao() {
		return roleDao;
	}

	@Autowired
	public void setRoleDao(BaseDaoI<Role> roleDao) {
		this.roleDao = roleDao;
	}

	public BaseDaoI<UserRole> getUserRoleDao() {
		return userRoleDao;
	}

	@Autowired
	public void setUserRoleDao(BaseDaoI<UserRole> userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	public BaseDaoI<User> getBaseDao() {
		return baseDao;
	}

	@Autowired
	public void setBaseDao(BaseDaoI<User> baseDao) {
		this.baseDao = baseDao;
	}

	@CacheEvict(value = "UserCache", allEntries = true)
	@Transactional(readOnly = true)
	public UserI login(UserI user) {
		User u = baseDao.get("from User u where u.loginCode=? and u.loginPass=?",user.getLoginCode(), user.getLoginPass());
		if (u != null) {
			BeanUtils.copyProperties(u, user);
			return user;
		}
		return null;
	}
 
	@CacheEvict(value = "UserCache", allEntries = true)
	public UserI edit(UserI user) {
		
		User u= baseDao.get(User.class,user.getId());
		
		if(!(user.getLoginPass().equals("") || user.getLoginPass()==null)){
			u.setLoginPass(Encrypt.e(user.getLoginPass()));
		}
		u.setModifyOperDate(new Date());
		BeanUtils.copyProperties(user,u);
		
		List<UserRole> syuserSyroleList = userRoleDao.find("from UserRole t where t.user=?", u);
		if (syuserSyroleList != null && syuserSyroleList.size() > 0) {
			for (UserRole ur : syuserSyroleList) {
				userRoleDao.delete(ur);
			}
		}
		 
		 if(!(user.getRoleId()==null || user.getRoleId().equals(""))){
			for (String id : user.getRoleId().split(",")) {
				UserRole ur = new UserRole();
				ur.setId(UUID.randomUUID().toString());
				ur.setRole(roleDao.get(Role.class,id));
				ur.setUser(u);
				userRoleDao.save(ur);
			}
		}
		 
		return user;
	}

	@CacheEvict(value = "UserCache", allEntries = true)
	public UserI reg(UserI user) {
		return user;
	}
	
	@CacheEvict(value = "UserCache", allEntries = true)
	public UserI add(UserI user) {
		UserI loginUser = loginUser();
		user.setId(UUID.randomUUID().toString());
		user.setLoginPass(Encrypt.e(user.getLoginPass()));
		User u = new User();
		BeanUtils.copyProperties(user,u);
		u.setStatus(1);
		u.setCreateOperDate(new Date());
		u.setCreateOperId(loginUser.getId());
		baseDao.save(u);
		if(!(user.getRoleId()==null || user.getRoleId().equals(""))){
			for (String id : user.getRoleId().split(",")) {
				UserRole ur = new UserRole();
				ur.setId(UUID.randomUUID().toString());
				ur.setRole(roleDao.get(Role.class,id));
				ur.setUser(u);
				userRoleDao.save(ur);
			}
		}
		return user;
	}
	
	@CacheEvict(value = "UserCache", allEntries = true)
	public void del(String ids) {
		for (String id : ids.split(",")) {
			User u = baseDao.get(User.class, id);
			if (u != null) {
				Set<UserRole> syuserSyroleSet = u.getRoles();
				if (syuserSyroleSet != null && syuserSyroleSet.size() > 0) {
					List<UserRole> syuserSyroleList = userRoleDao.find("from UserRole t where t.user=?", u);
					if (syuserSyroleList != null && syuserSyroleList.size() > 0) {
						for (UserRole syuserSyrole : syuserSyroleList) {
							userRoleDao.delete(syuserSyrole);
						}
					}
				}
				baseDao.delete(u);
			}
		}
	}

	//获取登录用户信息
	public UserI loginUser() {
		UserI ui = null;
		try{
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
			SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(ResourceUtil.getSessionInfoName());
			ui =  sessionInfo.getUser();
		}catch(Exception e){
			log.error("get LoginUser error : "+e.getMessage());
		}
		return ui;
	}
	
	public void loginFlag(HttpServletRequest request,HttpServletResponse response){
		UserI ui = loginUser();
		if (ui == null) {// 没有登录系统，或登录超时
			request.setAttribute("msg", "您没有登录或登录超时，请重新<a target='_parent' href='"+request.getContextPath()+"'><font color=blue>登录</font></a>！");
			try {
				request.getRequestDispatcher("error/authMsg.jsp").forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
